import Toast from '../../../components/dist/toast/toast';
const util = require("../../../utils/util.js");
const formatLocation = util.formatLocation;
const db = wx.cloud.database();
const icon = util.icon;
var app = getApp();
const buttons = [{
  label: '组件',
  icon,
},
{
  label: '页面',
  icon,
},
{
  label: '保存',
  icon,
},
{
  label: '预览',
  icon,
}
];

Page({
  data: {
    txtcolors: ['#FFFFFF', '#F5F5F5', '#DCDCDC', '#D3D3D3', '#808080', '	#000000', '#FFFF00', '#FFF8DC', '#FFEFDB', '#FFE7BA', '#FFE1FF', '#FF8C69', '#FF0000', '#EBEBEB', '#E6E6FA', '#DA70D6', '#CD3700', '#B3EE3A', '#ADD8E6', '#8968CD', '#7FFFD4', '#6495ED', '#00FFFF', '#FF00FF', '#9932CC', '#483D8B', '#B0E0E6', '#228B22', '#FFFFE0'],
    types: ['topLeft', 'topRight', 'bottomLeft', 'bottomRight', 'center'],
    typeIndex: 3,
    colors: ['light', 'stable', 'positive', 'calm', 'balanced', 'energized', 'assertive', 'royal', 'dark'],
    colorIndex: 6,
    dirs: ['horizontal', 'vertical', 'circle'],
    dirIndex: 1,
    sAngle: 0,
    eAngle: 360,
    spaceBetween: 10,
    buttons,
    color: app.ext.color,
    value: '',
    files: [],
    uploadImgCount: 0,
    uploadImgArry: [],
    background: ['demo-text-1', 'demo-text-2', 'demo-text-3'],
    vertical: false,
    tmpIconNum: 3,
    show: {
      middle: false,
      top: false,
      bottom: false,
      right: false,
      right2: false,
      right3: false
    },
    show_num: 0,
    show_type: '',
    diy: [],
    goodSelected: '',
    tmpGoodsImgs: '',
    tmpCurrentPageName: '首页',
    tmpCurrentPageI: 0,
    tmpAddPageName: '',
    tmpIconSelectIndex: 0,
    tmpFreePanelSubIndex: 0,
    all: [],
    pageType: '',
    showPageType: false,
    showPageAdd: false,
    actions: [{
      name: '一级页面'
    },
    {
      name: '二级页面'
    },
    {
      name: '三级页面'
    }
    ],
    tabbarbottom: 50,
    tabbarIconIndex: 0,
    startTime: 0,
    endTime: 0,
    callPanelShow: false,
    spinShow: true,
    diyId: '',
    diyEdit: 'false',
    diyProduct: 2 //1 零售小程序 2微站小程序
  },
  onChange(e) {
    this.setData({
      value: e.detail
    });
  },
  onLoad: function (options) {
    this.logMethod("onLoad");
    this.log(options);
    wx.showShareMenu();

    //1、预览 2、设计  user  admin  模板   确定 type product
    //跳转过来用户需要传 diyId diyEdit(0\1) diyType(admin user template) diyProduct(1\2)
    // let diyId = options.diyId;
    // let diyEdit = options.diyEdit;
    // let diyProduct = options.diyProduct;
    let diyId = app.globalData.diyId;
    let diyEdit = app.globalData.diyEdit;
    let diyProduct = app.globalData.diyProduct;

    if (wx.getStorageSync("isAdmin") && diyId == '') { //说明是管理员进入官网首页 提供编辑权限
      let tmpb = this.data.buttons;
      tmpb.push({
        label: '管理',
        icon,
      });
      this.setData({
        buttons: tmpb,
        diyEdit: 'true'
      });
    }
    let ti = (app.globalData.diyPageI == -1) ? 0 : app.globalData.diyPageI;

    if (diyId != '') { //说明是通过列表进入
      this.setData({
        diyId: diyId,
        diyEdit: diyEdit,
        diyProduct: diyProduct
      })
      db.collection('index_diy').doc(diyId).get().then(res => {
        console.log(res)
        if (res.data.all.length > 0) { //判断是否是首次diy编辑
          this.setData({
            all: res.data.all
          })
          this.getPageData(ti)
        } else { //初始化些数据

        }
        this.setData({
          spinShow: false
        });
      })
    } else {
      db.collection('index_diy').where({
        type: 'admin'
      }).get().then(res => {
        console.log(res)
        if (res.data[0].all.length > 0) { //判断是否是首次diy编辑
          this.setData({
            diyId: res.data[0]._id,
            all: res.data[0].all
          })
          this.getPageData(ti)
        }
        this.setData({
          spinShow: false
        });
      })
    }

    wx.setNavigationBarTitle({
      title: "首页",
    })
  },
  onShow: function () {
    var that = this;
    var pages = getCurrentPages();
    var currPage = pages[pages.length - 1];
    if (currPage.data.imgSelected) {
      let ui = that.data.diy;
      ui[that.data.show_num].vcon[that.data.tmpIconSelectIndex].url = currPage.data.imgSelected.url;

      that.setData({
        diy: ui
      })
    }
    if (currPage.data.goodSelected) {
      that.setData({
        goodSelected: currPage.data.goodSelected
      })
      let goodsDiy = that.data.diy
      if (goodsDiy[that.data.show_num].type == "goods") {
        goodsDiy[that.data.show_num].product_list[parseInt(that.data.tmpGoodsImgs)] = that.data.goodSelected;
      } else if (goodsDiy[that.data.show_num].type == "image") {
        goodsDiy[that.data.show_num].vcon[that.data.tmpGoodsImgs].type = 0; //商品是0  页面是1
        goodsDiy[that.data.show_num].vcon[that.data.tmpGoodsImgs].event = that.data.goodSelected.id;
      } else if (goodsDiy[that.data.show_num].type == "swiper") {
        //TODO imageUrl参数需重定义
        goodsDiy[that.data.show_num].vcon[parseInt(that.data.tmpGoodsImgs)].type = 0; //商品是0  页面是1 电话2 地图3 零售模板4 微站模板5
        goodsDiy[that.data.show_num].vcon[parseInt(that.data.tmpGoodsImgs)].event = that.data.goodSelected.id;
      } else if (goodsDiy[that.data.show_num].type == "menu") {
        //TODO imageUrl参数需重定义
        goodsDiy[that.data.show_num].vcon[parseInt(that.data.tmpGoodsImgs)].type = 0; //商品是0  页面是1
        goodsDiy[that.data.show_num].vcon[parseInt(that.data.tmpGoodsImgs)].event = that.data.goodSelected.id;
      } else if (goodsDiy[that.data.show_num].type == "freepanel") {
        //TODO imageUrl参数需重定义
        goodsDiy[that.data.show_num].vcon[parseInt(that.data.tmpGoodsImgs)].type = 0; //商品是0  页面是1
        goodsDiy[that.data.show_num].vcon[parseInt(that.data.tmpGoodsImgs)].event = that.data.goodSelected.id;
      }

      let a = that.data.all
      a[that.data.tmpCurrentPageI].content = goodsDiy
      that.setData({
        diy: goodsDiy,
        all: a
      })
    }
  },
  onShareAppMessage(options) {

  },
  onDiyAdd(e) {
    this.toggle('right');
    let tmpDiy = this.data.diy;
    let type = e.currentTarget.dataset.index;
    console.log(type)
    let mSearch = {
      type: 'search'
    };
    let mSwiper = {
      type: 'swiper',
      vcon: [{
        url: '../../../images/noimg2.png',
        type: '',
        event: '',
        event_url: ''
      }],
      indicatorDots: true,
      autoplay: false,
      duration: 500,
      interval: 2000,
      swiperHeight: 200
    };
    let mMenu = {
      type: 'menu',
      vcon: [{
        url: '../../../images/demoicon.png',
        title: '图标1',
        event: '',
        event_url: ''
      }, {
        url: '../../../images/demoicon.png',
        title: '图标2',
        event: '',
        event_url: ''
      }, {
        url: '../../../images/demoicon.png',
        title: '图标3',
        event: '',
        event_url: ''
      }]
    };
    let mText = {
      type: 'text',
      context: '我是文本',
      layoutLeft: 30
    };
    let mImage = {
      type: 'image',
      ntype: 1,
      vcon: [{
        url: '../../../images/noimg2.png',
        event: '',
        event_url: '',
        type: '',
        h: 200,
        w: 100,
        imageUpDown: 0,
        imageLeftRight: 0
      }]
    };
    let mGoods = {
      type: 'goods',
      show_type: 1,
      product_list: [{
        id: '1',
        img_url: '/images/noimg2.png',
        name: '商品',
        price: '0.2',
        price_org: '0.1',
        sale: '10',
        subname: '描述'
      }]
    };
    let mTabbar = {
      type: 'tabbar',
      current: 'homepage',
      vcon: [{
        icon: 'homepage',
        current_icon: 'homepage_fill',
        title: '首页',
        event: '',
        event_url: '',
        type: ''
      }, {
        icon: 'remind',
        current_icon: 'remind_fill',
        title: '动态',
        event: '',
        event_url: '',
        type: ''
      }, {
        icon: 'mine',
        current_icon: 'mine_fill',
        title: '我的',
        event: '',
        event_url: '',
        type: ''
      }]
    };
    let mNoticebar = {
      type: 'noticebar',
      context: '通知栏消息'
    };
    let mFreepanel = {
      type: 'freepanel',
      height: '300',
      width: '750',
      vcon: [{
        img: '1',
        x: '0',
        y: '0',
        w: '100',
        h: '100',
        url: '../../../images/noimg2.png',
        event: '',
        event_url: '',
        type: '',
        border: 'none'
      }, {
        img: '0',
        x: '0',
        y: '0',
        w: '100',
        h: '30',
        content: 'hello',
        event: '',
        event_url: '',
        type: '',
        border: 'none',
        bgcolor: '#000000'
      }]
    };
    if (type == 'search') {
      tmpDiy.push(mSearch);
    } else if (type == 'swiper') {
      tmpDiy.push(mSwiper);
    } else if (type == 'menu') {
      tmpDiy.push(mMenu);
    } else if (type == 'text') {
      tmpDiy.push(mText);
    } else if (type == 'image') {
      tmpDiy.push(mImage);
    } else if (type == 'goods') {
      tmpDiy.push(mGoods);
    } else if (type == 'tabbar') {
      this.setData({
        tabbarbottom: 50
      })
      tmpDiy.push(mTabbar);
    } else if (type == 'noticebar') {
      tmpDiy.push(mNoticebar);
    } else if (type == 'freepanel') {
      tmpDiy.push(mFreepanel);
    }
    let tmpDiyD = {
      name: this.data.tmpCurrentPage,
      content: tmpDiy
    };
    let tmpAll = this.data.all
    tmpAll[this.data.tmpCurrentPageI].content = tmpDiy
    console.log(tmpDiy)
    this.setData({
      diy: tmpDiy,
      all: tmpAll
    });
  },
  getPageData: function (i) {
    this.setData({
      diy: this.data.all[i].content,
      tmpCurrentPageI: i
    })

  },
  onDiyEdit(e) {
    console.log(e)
    if (e.currentTarget.dataset.type == 'swiper') {
      if (this.data.diy[e.currentTarget.dataset.index].vcon[0].url == '../../../images/noimg2.png')
        this.setData({
          files: []
        })
      else
        this.setData({
          files: this.data.diy[e.currentTarget.dataset.index].vcon
        })
      console.log("111111");
      console.log(this.data.files);
    } else if (e.currentTarget.dataset.type == 'freepanel-image') {
      this.setData({
        tmpFreePanelSubIndex: e.currentTarget.dataset.cellindex
      })
    } else if (e.currentTarget.dataset.type == 'freepanel-text') {
      this.setData({
        tmpFreePanelSubIndex: e.currentTarget.dataset.cellindex
      })
    }
    this.toggle('bottom');
    this.setData({
      show_num: e.currentTarget.dataset.index,
      show_type: e.currentTarget.dataset.type
    })
    console.log(this.data.show_type)
  },
  onDiyCopy(e) {
    let tt = this.data.diy;
    tt.push(tt[e.currentTarget.dataset.index])
    this.setData({
      diy: tt
    })
  },
  onDiyDelete(e) {
    let tt = this.data.diy;
    tt.splice(e.currentTarget.dataset.index, 1)
    this.setData({
      diy: tt
    })
    let type = e.currentTarget.dataset.index;
    if (type == "tabbar") {
      this.setData({
        tabbarbottom: 0
      })
    }
  },
  onDiyMoveUp(e) {

  },
  onDiyMoveDown(e) {

  },

  onSearch(event) {
    if (this.data.value) {
      // wx.showToast({
      //   title: '搜索：' + this.data.value,
      //   icon: 'none'
      // });
      wx.navigateTo({
        url: '../../../pages/shop/product/product-list/index?text=' + this.data.value,
      })
    }
  },

  onCancel() {
    wx.showToast({
      title: '取消',
      icon: 'none'
    });
  },

  onClear() {
    wx.showToast({
      title: '清空',
      icon: 'none'
    });
  },
  changeIndicatorDots: function (e) {
    let ui = this.data.diy;
    ui[this.data.show_num].indicatorDots = e.detail.value
    this.setData({
      diy: ui
    })
  },
  changeAutoplay: function (e) {
    let ui = this.data.diy;
    ui[this.data.show_num].autoplay = e.detail.value;
    this.setData({
      diy: ui
    })
  },
  intervalChange: function (e) {
    let ui = this.data.diy;
    ui[this.data.show_num].interval = e.detail.value

    this.setData({
      diy: ui
    })

  },
  durationChange: function (e) {
    let ui = this.data.diy;
    ui[this.data.show_num].duration = e.detail.value

    this.setData({
      diy: ui
    })
  },
  swiperHeightChange: function (e) {
    let ui = this.data.diy;
    ui[this.data.show_num].swiperHeight = e.detail.value

    this.setData({
      diy: ui
    })
  },
  imageHeightChange: function (e) {
    console.log(e.currentTarget.dataset.index);
    let mt = e.currentTarget.dataset.index;
    if (mt >= 2) {
      mt = 2
    }
    let ui = this.data.diy;
    ui[this.data.show_num].vcon[mt].h = e.detail.value

    this.setData({
      diy: ui
    })
  },
  imageWidthChange: function (e) {
    console.log(e.currentTarget.dataset.index);
    let mt = e.currentTarget.dataset.index;
    if (mt >= 2) {
      mt = 2
    }
    let ui = this.data.diy;
    ui[this.data.show_num].vcon[mt].w = e.detail.value

    this.setData({
      diy: ui
    })
    console.log(this.data.diy)
  },
  imageUpDownChange: function (e) {
    console.log(e.currentTarget.dataset.index);
    let mt = e.currentTarget.dataset.index;
    if (mt >= 2) {
      mt = 2
    }
    let ui = this.data.diy;
    ui[this.data.show_num].vcon[mt].imageUpDown = e.detail.value

    this.setData({
      diy: ui
    })
    console.log(this.data.diy)
  },
  imageLeftRightChange: function (e) {
    console.log(e.currentTarget.dataset.index);
    let mt = e.currentTarget.dataset.index;
    if (mt >= 2) {
      mt = 2
    }
    let ui = this.data.diy;
    ui[this.data.show_num].vcon[mt].imageLeftRight = e.detail.value

    this.setData({
      diy: ui
    })
    console.log(this.data.diy)
  },
  addComponent: function (e) {

  },

  toggle(type) {
    this.setData({
      [`show.${type}`]: !this.data.show[type]
    });
  },

  togglePopup() {
    this.toggle('middle');
  },

  toggleRightPopup() {
    this.toggle('right');
  },

  toggleRightPopup2() {
    this.toggle('right2');
  },

  toggleRightPopup3() {
    this.toggle('right3');
  },

  toggleBottomPopup() {
    this.toggle('bottom');
  },

  toggleTopPopup() {
    this.toggle('top');
    setTimeout(() => {
      this.toggle('top');
    }, 2000);
  },
  chooseImage: function (e) {
    var that = this;
    var images = that.data.files;
    wx.chooseImage({
      count: 6 - images.length,
      sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      success: function (res) {
        console.log(res)
        // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
        let tmp = {
          event: "",
          event_url: "",
          type: "",
          url: ""
        };
        tmp.url = res.tempFilePaths[0];
        that.setData({
          files: that.data.files.concat(tmp)
        });
        console.log("2222");
        console.log(that.data.files);
      }
    })
  },
  previewImage: function (e) {
    wx.previewImage({
      current: e.currentTarget.id, // 当前显示图片的http链接
      urls: this.data.files // 需要预览的图片http链接列表
    })
  },
  deleteImage: function (e) {
    var that = this;
    var images = that.data.files;
    var index = e.currentTarget.dataset.index; //获取当前长按图片下标
    wx.showModal({
      title: '系统提醒',
      content: '确定要删除此图片吗？',
      success: function (res) {
        if (res.confirm) {
          images.splice(index, 1);
          let tt = that.data.diy;
          //tt[that.data.show_num].vcon.splice(index, 1)
          that.setData({
            diy: tt
          })
          console.log(images);
        } else if (res.cancel) {
          return false;
        }
        that.setData({
          files: images
        });
      }
    })
  },
  uploadImg: function (e) {
    wx.showLoading({
      title: '数据同步中',
    })
    let ti = 0;
    for (let i = 0; i < this.data.files.length; i++) {
      const filePath = this.data.files[i].url;
      if (filePath.indexOf("cloud") != -1) {
        continue;
      } else {
        ti++;
      }
    }
    console.log("ti" + ti);
    console.log(this.data.diy);
    let tj = 0;
    for (let i = 0; i < this.data.files.length; i++) {
      const filePath = this.data.files[i].url;
      if (filePath.indexOf("cloud") != -1) {
        continue;
      }
      tj++;
      // 上传图片
      const cloudPath = 'dzimg/' + wx.getStorageSync('openid') + '/swiper/' + (new Date()).valueOf() + filePath.match(/\.[^.]+?$/)[0];
      wx.cloud.uploadFile({
        cloudPath,
        filePath,
        success: res => {
          console.log('[上传文件] 成功：', res);
          let ui = this.data.diy;
          let tmp = {
            event: "",
            event_url: "",
            type: "",
            url: ""
          };
          tmp.url = res.fileID;
          console.log("1");
          // ui[this.data.show_num].vcon[tj-1].url = res.fileID
          // console.log("2")
          ui[this.data.show_num].vcon.push(tmp);
          if (ui[this.data.show_num].vcon[0].url.indexOf("cloud") != -1) {

          } else {
            ui[this.data.show_num].vcon.splice(0, 1);
          }
          this.setData({
            diy: ui
          })
          console.log(3)
          this.savePicture(res.fileID, 1);
          //TODO resfileId 到DIY json
          console.log("tj" + tj);
          if (tj == ti)
            wx.hideLoading();
        },
        fail: e => {
          console.error('[上传文件] 失败：', e)
          wx.showToast({
            icon: 'none',
            title: '上传失败',
          })
          wx.hideLoading();
        },
        complete: () => { }
      })

    }

  },
  onMenuChange: function (e) {
    console.log(e.detail)
    console.log(this.data.tmpIconNum)
    let mt = {
      url: '../../../images/demoicon.png',
      title: '图标'
    }
    let menuDiy = this.data.diy

    if (menuDiy[this.data.show_num].vcon.length > parseInt(e.detail)) {
      menuDiy[this.data.show_num].vcon.splice(menuDiy[this.data.show_num].vcon.length - 1, 1)
      this.setData({
        diy: menuDiy
      })

    } else if (menuDiy[this.data.show_num].vcon.length < parseInt(e.detail)) {
      console.log(345)
      menuDiy[this.data.show_num].vcon.push(mt)
      this.setData({
        diy: menuDiy
      })
    }
    console.log(menuDiy[this.data.show_num].vcon)
    // this.setData({
    //   tmpIconNum:e.detail
    // })

  },
  onImageChange: function (e) {
    console.log(e.detail)
    let mt = {
      url: '../../../images/noimg2.png',
      event: '',
      event_url: '',
      type: '',
      h: 200,
      w: 100,
      imageUpDown: 0,
      imageLeftRight: 0
    };
    let imageDiy = this.data.diy;

    if (parseInt(e.detail) == 1) {
      imageDiy[this.data.show_num].vcon.splice(imageDiy[this.data.show_num].vcon.length - 1, 1);
      imageDiy[this.data.show_num].ntype = 1;
    } else if (parseInt(e.detail) == 2) {
      if (imageDiy[this.data.show_num].vcon.length > parseInt(e.detail)) {
        imageDiy[this.data.show_num].vcon.splice(imageDiy[this.data.show_num].vcon.length - 1, 1)
      } else if (imageDiy[this.data.show_num].vcon.length < parseInt(e.detail)) {
        imageDiy[this.data.show_num].vcon.push(mt)
      }
      imageDiy[this.data.show_num].ntype = 2;
    } else if (parseInt(e.detail) == 3) {
      if (imageDiy[this.data.show_num].vcon.length > parseInt(e.detail)) { } else if (imageDiy[this.data.show_num].vcon.length < parseInt(e.detail)) {
        imageDiy[this.data.show_num].vcon.push(mt)
      }
      imageDiy[this.data.show_num].ntype = 3;
    } else if (parseInt(e.detail) == 4) {
      imageDiy[this.data.show_num].ntype = 4;
    } else if (parseInt(e.detail) == 5) {
      imageDiy[this.data.show_num].ntype = 5;
    }
    this.setData({
      diy: imageDiy
    })
    console.log(this.data.diy)
  },
  onTabbarChange: function (e) {
    console.log(this.data.tmpIconNum)
    let mt = {
      icon: 'mine',
      current_icon: 'mine_fill',
      title: '我的',
      event: '',
      event_url: '',
      type: ''
    }
    let menuDiy = this.data.diy

    if (menuDiy[this.data.show_num].vcon.length > parseInt(e.detail)) {
      menuDiy[this.data.show_num].vcon.splice(menuDiy[this.data.show_num].vcon.length - 1, 1)
      this.setData({
        diy: menuDiy
      })

    } else if (menuDiy[this.data.show_num].vcon.length < parseInt(e.detail)) {
      console.log(345)
      menuDiy[this.data.show_num].vcon.push(mt)
      this.setData({
        diy: menuDiy
      })
    }

  },
  chooseIconImageEvent: function (e) {
    let index = e.currentTarget.dataset.index;
    this.setData({
      tmpIconSelectIndex: index
    })
    this.toggleRightPopup2();
  },
  chooseIconImage: function (e) {
    console.log(e)
    let index = e.currentTarget.dataset.index;
    console.log(index + "aaaaa")
    var that = this;
    wx.chooseImage({
      count: 1,
      sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      success: function (res) {
        console.log(res)
        // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
        that.uploadIconImg(res.tempFilePaths[0], index)
      }
    })
  },
  uploadIconImg: function (e, i) {
    console.log("qqq" + i + "ee" + e)
    wx.showLoading({
      title: '数据同步中',
    })
    const filePath = e
    // 上传图片
    const cloudPath = 'dzimg/' + wx.getStorageSync('openid') + '/icon/' + (new Date()).valueOf() + filePath.match(/\.[^.]+?$/)[0]
    wx.cloud.uploadFile({
      cloudPath,
      filePath,
      success: res => {
        console.log('[上传文件] 成功：', res)
        let ui = this.data.diy;
        ui[this.data.show_num].vcon[i].url = res.fileID

        this.setData({
          diy: ui
        })
        this.savePicture(res.fileID, 0);
        wx.hideLoading();
      },
      fail: e => {
        console.error('[上传文件] 失败：', e)
        wx.showToast({
          icon: 'none',
          title: '上传失败',
        })
        wx.hideLoading();
      },
      complete: () => { }
    })
  },
  onIconTitleChange: function (e) {
    console.log(e)
    let ui = this.data.diy;
    ui[this.data.show_num].vcon[e.currentTarget.dataset.index].title = e.detail

    this.setData({
      diy: ui
    })

  },
  chooseIconEvent: function (e) {
    let index = e.currentTarget.dataset.index;
    this.setData({
      tmpIconSelectIndex: index
    })
    this.toggleRightPopup2();
  },
  onTextChange: function (e) {
    console.log(e)
    let ui = this.data.diy;
    ui[this.data.show_num].context = e.detail

    this.setData({
      diy: ui
    })

  },

  onNoticebarChange: function (e) {
    console.log(e)
    let ui = this.data.diy;
    ui[this.data.show_num].context = e.detail

    this.setData({
      diy: ui
    })

  },
  onTextSlidChange: function (e) {
    let ui = this.data.diy;
    ui[this.data.show_num].layoutLeft = e.detail;

    this.setData({
      diy: ui
    })

  },
  chooseDiySystemImage: function (e) {
    let index = e.currentTarget.dataset.index;
    this.setData({
      tmpIconSelectIndex: index
    })
    wx.navigateTo({
      url: '../../../pages/dy/pictures/index',
      complete: function () {
        console.log("开始了")
      }
    })
  },
  chooseDiyImage: function (e) {
    let index = e.currentTarget.dataset.index;

    console.log(e)
    var that = this;
    wx.chooseImage({
      count: 1,
      sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      success: function (res) {
        console.log(res)
        // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
        that.uploadDiyImg(res.tempFilePaths[0], index)
      }
    })
  },
  uploadDiyImg: function (e, i) {
    console.log("qqq" + i + "ee" + e)
    wx.showLoading({
      title: '数据同步中',
    })
    const filePath = e
    // 上传图片
    const cloudPath = 'dzimg/' + wx.getStorageSync('openid') + '/image/' + (new Date()).valueOf() + filePath.match(/\.[^.]+?$/)[0]
    console.log(cloudPath)
    wx.cloud.uploadFile({
      cloudPath,
      filePath,
      success: res => {
        console.log('[上传文件] 成功：', res)
        let ui = this.data.diy;
        ui[this.data.show_num].vcon[i].url = res.fileID;

        this.setData({
          diy: ui
        })
        this.savePicture(res.fileID, 1);
        wx.hideLoading();
      },
      fail: e => {
        console.error('[上传文件] 失败：', e)
        wx.showToast({
          icon: 'none',
          title: '上传失败',
        })
        wx.hideLoading();
      },
      complete: () => { }
    })
  },
  onGoodsChange: function (e) {
    console.log(e.detail)
    console.log(this.data.diy[this.data.show_num].product_list.length)
    let mt = {
      id: '1',
      img_url: '/images/noimg2.png',
      name: '商品',
      price: '0.2',
      price_org: '0.1',
      sale: '10',
      subname: '描述'
    }
    let menuDiy = this.data.diy
    if (parseInt(this.data.diy[this.data.show_num].product_list.length) > parseInt(e.detail)) {
      menuDiy[this.data.show_num].product_list.splice(this.data.diy[this.data.show_num].product_list.length - 1, 1)
      this.setData({
        diy: menuDiy
      })
      console.log(23)
    } else if (parseInt(this.data.diy[this.data.show_num].product_list.length) < parseInt(e.detail)) {
      console.log(345)
      menuDiy[this.data.show_num].product_list.push(mt)
      this.setData({
        diy: menuDiy
      })
    }
  },
  chooseGoodsImage: function (e) {
    let index = e.currentTarget.dataset.index;
    let that = this;
    that.setData({
      tmpGoodsImgs: index
    })
    wx.navigateTo({
      url: '../../../pages/dy/product/index',
      complete: function () {
        console.log("开始了")
      }
    })
  },
  release: function (e) {
    console.log(this.data.all)
    let ta = this.data.all;
    for (var i = 0; i < ta.length; i++) {
      for (var j = 0; j < ta[i].content.length; j++) {
        if (ta[i].content[j].type == "freepanel") {
          for (var k = 0; k < ta[i].content[j].vcon.length; k++) {
            ta[i].content[j].vcon[k].border = "none"
          }
        }
      }
    }
    this.setData({
      all: ta
    })
    console.log(this.data.all)
    console.log(this.data.diyId)
    db.collection('index_diy').doc(this.data.diyId).update({
      // data 传入需要局部更新的数据
      data: {
        createtime: util.formatTime(new Date()),
        all: this.data.all
      },
      success(res) {
        // res 是一个对象，其中有 _id 字段标记刚创建的记录的 id
        console.log(res)
        wx.showToast({
          title: '发布成功',
        })
      },
      fail: console.error
    })

  },
  closePagesList: function (e) {
    this.toggle('right2');
  },
  addPage: function (e) {
    if (this.data.pageType == "") {
      Toast.fail('请选择页面分类');
      return;
    }
    if (this.data.tmpAddPageName == "") {
      Toast.fail('请输入页面名称');
      return;
    }
    let a = this.data.all
    let url = '';
    if (this.data.pageType == this.data.actions[0].name) {
      url = '../../../pages/com/one/index';
    } else if (this.data.pageType == this.data.actions[1].name) {
      url = '../../../pages/com/two/index';
    } else if (this.data.pageType == this.data.actions[2].name) {
      url = '../../../pages/com/three/index';
    }
    a.push({
      name: this.data.tmpAddPageName,
      type: this.data.pageType,
      url: url,
      content: []
    })
    this.setData({
      all: a
    })
    this.setData({
      tmpAddPageName: '',
      pageType: ''
    })
    Toast.success('添加成功')
  },
  pageNameChange: function (e) {
    console.log(e)
    this.setData({
      tmpAddPageName: e.detail
    })
  },
  updatePage: function (e) {
    console.log(e)
    // for (var i = 0; i < this.data.all.length; i++) {
    //   if (this.data.all[i].name == e.currentTarget.dataset.name) {
    //     this.setData({
    //       tmpCurrentPageName: e.currentTarget.dataset.name
    //     })
    this.getPageData(e.currentTarget.dataset.index)
    //   }
    // }
    this.toggleRightPopup2()

    wx.setNavigationBarTitle({
      title: this.data.all[e.currentTarget.dataset.index].name,
    })
  },
  delPage: function (e) {
    for (var i = 0; i < this.data.all.length; i++) {
      if (this.data.all[i].name == e.currentTarget.dataset.name) {
        let tt = this.data.all;
        tt.splice(i, 1)
        this.setData({
          all: tt
        })
      }
    }
  },
  copyPage: function (e) {
    let c = 0;
    let m = 0;
    for (var i = 0; i < this.data.all.length; i++) {
      if (this.data.all[i].name == e.currentTarget.dataset.name) {
        m = i;
      }
    }
    let tt = this.data.all;
    var dd = {
      content: [],
      name: "",
      url: "",
      type: ""
    };
    dd.name = tt[m].name + "2"
    dd.url = tt[m].url;
    dd.type = tt[m].type;
    dd.content = tt[m].content;
    tt.push(dd);
    console.log(tt)
    this.setData({
      all: tt
    })
  },
  selectPage: function (e) {
    console.log("selectPage")
    console.log(this.data.diy)
    console.log(e.currentTarget.dataset.url)
    // for (var i = 0; i < this.data.all.length; i++) {
    //   if (this.data.all[i].name == e.currentTarget.dataset.name) {
    let ui = this.data.diy;
    if (ui[this.data.show_num].type == "menu") {
      ui[this.data.show_num].vcon[this.data.tmpIconSelectIndex].event = e.currentTarget.dataset.index;
      ui[this.data.show_num].vcon[this.data.tmpIconSelectIndex].event_url = e.currentTarget.dataset.url;
    } else if (ui[this.data.show_num].type == "image") {
      ui[this.data.show_num].vcon[this.data.tmpIconSelectIndex].event = e.currentTarget.dataset.index;
      ui[this.data.show_num].vcon[this.data.tmpIconSelectIndex].event_url = e.currentTarget.dataset.url;
      ui[this.data.show_num].vcon[this.data.tmpIconSelectIndex].type = 1;

    } else if (ui[this.data.show_num].type == "swiper") {
      ui[this.data.show_num].vcon[this.data.tmpIconSelectIndex].event = e.currentTarget.dataset.index;
      ui[this.data.show_num].vcon[this.data.tmpIconSelectIndex].event_url = e.currentTarget.dataset.url;
      ui[this.data.show_num].vcon[this.data.tmpIconSelectIndex].type = 1;
    } else if (ui[this.data.show_num].type == "tabbar") {
      console.log(ui[this.data.show_num].vcon[this.data.tmpIconSelectIndex].event_url)
      ui[this.data.show_num].vcon[this.data.tmpIconSelectIndex].event = e.currentTarget.dataset.index;
      ui[this.data.show_num].vcon[this.data.tmpIconSelectIndex].event_url = e.currentTarget.dataset.url;
      ui[this.data.show_num].vcon[this.data.tmpIconSelectIndex].type = 1;
      console.log(ui[this.data.show_num].vcon[this.data.tmpIconSelectIndex].event_url)
    } else if (ui[this.data.show_num].type == "freepanel") {
      ui[this.data.show_num].vcon[this.data.tmpIconSelectIndex].event = e.currentTarget.dataset.index;
      ui[this.data.show_num].vcon[this.data.tmpIconSelectIndex].event_url = e.currentTarget.dataset.url;
      ui[this.data.show_num].vcon[this.data.tmpIconSelectIndex].type = 1;
    }
    this.setData({
      diy: ui
    })
    // }

    // }
    console.log(this.data.diy)
    this.toggleRightPopup2()
  },
  goOtherPage: function (e) {
    this.clickEvent(e.currentTarget.dataset.type, e.currentTarget.dataset.event)
  },
  upmove: function (e) {
    let index = e.currentTarget.dataset.index;
    let ui = this.data.diy;
    let tmp = {};
    if (parseInt(index) > 0) {
      if (ui.length > 1) {
        tmp = ui[index];
        ui[index] = ui[index - 1];
        ui[index - 1] = tmp;
        this.setData({
          diy: ui
        })
      }
    }
  },
  downmove: function (e) {
    let index = e.currentTarget.dataset.index;
    let ui = this.data.diy;
    let tmp = {};
    if (ui.length > 1) {
      if (parseInt(index) != ui.length - 1) {
        tmp = ui[index];
        ui[index] = ui[index + 1];
        ui[index + 1] = tmp;
        this.setData({
          diy: ui
        })
      }
    }
  },
  addPageSelectType: function (e) {
    this.setData({
      showPageType: true
    })
  },
  onClose() {
    this.setData({
      showPageType: false
    });
  },

  onSelect(event) {
    console.log(event.detail);
    this.setData({
      pageType: event.detail.name,
      showPageType: false
    })

  },
  goProductDetail: function (e) {
    this.goProductPage(e.currentTarget.dataset.id);
  },
  goProductPage: function (e) {
    wx.navigateTo({

      url: `/pages/shop/product/product-detail/index?id=${e}`
    });
  },
  goFirst(e) {
    app.globalData.diyEdit = "false";
    app.globalData.diyPageI = -1;
    if (this.data.diyProduct == 1) {
      wx.switchTab({
        url: '../../../pages/com/index/index',
      })
    } else {
      wx.redirectTo({
        url: '../../../pages/com/home/index',
      })
    }
  },
  goManage(e) {
    wx.navigateTo({
      url: '../../../pages/manage/template-man/index',
    })
  },
  onBottomMenuChange: function (e) {
    console.log(e.detail)
    if (e.detail.index == 0) {
      this.toggleRightPopup()
    } else if (e.detail.index == 1) {
      this.toggleRightPopup2()
    } else if (e.detail.index == 2) {
      this.release()
    } else if (e.detail.index == 3) {
      this.goFirst()
    } else if (e.detail.index == 4) {
      this.goManage()
    }
  },
  onClickShowPageAdd: function (e) {
    if (this.data.showPageAdd) {
      this.setData({
        showPageAdd: false
      })
    } else {
      this.setData({
        showPageAdd: true
      })
    }
  },
  onTabbarhandleChange({
    detail
  }) {
    console.log(detail.key)
    if (detail.key == 'addressbook') {
      wx.redirectTo({
        url: '../../../pages/manage/xcx-man/index',
      })
      return;
    }
    let tabDiy = this.data.diy;
    for (var i = 0; i < tabDiy.length; i++) {
      if (tabDiy[i].type == 'tabbar') {
        for (var j = 0; j < tabDiy[i].vcon.length; j++) {
          if (tabDiy[i].vcon[j].icon == detail.key) {
            // wx.setStorageSync('tmpCurrentPageName', tabDiy[i].vcon[j].event)
            app.globalData.diyId = this.data.diyId;
            app.globalData.diyProduct = this.data.diyProduct;
            app.globalData.diyEdit = this.data.diyEdit;
            app.globalData.diyPageI = tabDiy[i].vcon[j].event;
            console.log(tabDiy[i].vcon[j].event_url);
            wx.redirectTo({
              url: tabDiy[i].vcon[j].event_url
            });
            return false;
          }
        }
      }
    }
  },
  onTabbarIconAdd(e) {
    this.toggle('right3');
    let icon = e.currentTarget.dataset.index;
    let fill = e.currentTarget.dataset.fill;
    let i = this.data.tabbarIconIndex;
    let ui = this.data.diy;
    ui[this.data.show_num].vcon[i].icon = icon;
    ui[this.data.show_num].vcon[i].current_icon = fill;
    this.setData({
      diy: ui
    })
  },
  chooseTabbarIconImage(e) {
    let i = e.currentTarget.dataset.index;
    this.setData({
      tabbarIconIndex: i
    })
    this.toggleRightPopup3();
  },
  onHandleDefaultClickChange({
    detail = {}
  }) {
    let ui = this.data.diy;
    ui[this.data.show_num].current = detail.value;
    this.setData({
      diy: ui
    })
  },
  savePicture: function (u, t) {
    db.collection('pictures').add({
      // data 字段表示需新增的 JSON 数据
      data: {
        url: u,
        type: t, //0是icon   1是pic
        createtime: util.formatTime(new Date())
      },
      success(res) {
        // res 是一个对象，其中有 _id 字段标记刚创建的记录的 id
        console.log(res)
      },
      fail: console.error
    })
  },

  getNodeInfo(e) {
    let index = e.currentTarget.dataset.cellindex;
    let screenWidth = wx.getSystemInfoSync().windowWidth;
    const $ = wx.createSelectorQuery()
    const target = $.select('.target' + e.currentTarget.dataset.index + '-' + index)
    target.boundingClientRect()

    $.exec((res) => {
      const rect = res[0]
      if (rect) {
        const metrics = []
        // eslint-disable-next-line
        let tmp = this.data.diy;
        console.log("hahah")
        console.log(e.currentTarget.dataset.index)
        console.log(index)
        for (const key in rect) {
          if (key !== 'id' && key !== 'dataset') {
            const val = rect[key]
            // metrics.push({ key, val })

            if (key == 'left') {
              tmp[e.currentTarget.dataset.index].vcon[index].x = (750 * val) / screenWidth;

              console.log(tmp[e.currentTarget.dataset.index].vcon[index].x)
              console.log(this.data.diy[e.currentTarget.dataset.index].vcon[index].x)
            } else if (key == 'top') {

              let query = wx.createSelectorQuery()
              query.select('#index-nav' + e.currentTarget.dataset.index).boundingClientRect((rect) => {
                let top = rect.top
                console.log("234")
                console.log(top)
                tmp[e.currentTarget.dataset.index].vcon[index].y = (750 * (val - top)) / screenWidth;
                console.log(tmp[e.currentTarget.dataset.index].vcon[index].y)

              }).exec()

            }
          }
        }

      }
    })
  },

  getZoomInfo(e) {
    let index = e.currentTarget.dataset.cellindex;
    let screenWidth = wx.getSystemInfoSync().windowWidth;
    const $ = wx.createSelectorQuery()
    const target = $.select('.target' + e.currentTarget.dataset.index + '-' + index)
    target.boundingClientRect()
    let d = this.data.dd;
    $.exec((res) => {
      const rect = res[0]
      if (rect) {
        const metrics = []
        // eslint-disable-next-line
        let da = this.data.diy[e.currentTarget.dataset.index].vcon;
        for (const key in rect) {
          if (key !== 'id' && key !== 'dataset') {
            const val = rect[key]
            if (key == 'left') {
              da[index].x = (750 * val) / screenWidth;
            } else if (key == 'top') {

              let query = wx.createSelectorQuery()
              query.select('#index-nav' + e.currentTarget.dataset.index).boundingClientRect((rect) => {
                let top = rect.top
                console.log(top)
                da[index].y = (750 * (val - top)) / screenWidth;
                console.log(da[index].y)
              }).exec()

            } else if (key == 'width') {
              // d[index].w = val;
              da[index].w = (750 * val) / screenWidth;
            } else if (key == 'height') {
              // d[index].h = val;
              da[index].h = (750 * val) / screenWidth;
            }
          }
        }
        // this.setData({
        //   dd: d
        // })
      }
    })
  },
  onFreePanelImageClick(e) {
    if (this.endTime - this.startTime < 350) {
      console.log("点击");
    } else {
      return;
    }
    let edit = this.data.diyEdit;
    let tmp = this.data.diy;
    let cellindex = e.currentTarget.dataset.cellindex;
    let index = e.currentTarget.dataset.index;
    if (edit == "true") {
      tmp[index].vcon[cellindex].border = "solid";
      for (var i = 0; i < tmp[e.currentTarget.dataset.index].vcon.length; i++) {
        if (i != cellindex) {
          tmp[index].vcon[i].border = "none";
        }
      }
      console.log(e.currentTarget.dataset.index)
      console.log(e.currentTarget.dataset.cellindex)

      console.log(this.data.all)
      console.log(this.data.diy)
      this.setData({
        diy: tmp
      })
      console.log("hhhhhhhhh")
      console.log(this.data.all)
      console.log(this.data.diy)
    } else {
      //跳转
      let type = tmp[index].vcon[cellindex].type;
      let event = tmp[index].vcon[cellindex].event;
      this.clickEvent(type, event)
    }
  },
  /**
   * --自由面板--
   * 添加文本
   */
  addFreePanelText(e) {
    let mt = {
      img: '0',
      x: '0',
      y: '0',
      w: '100',
      h: '30',
      content: 'hello',
      event: '',
      event_url: '',
      type: '',
      border: 'none',
      bgcolor: '#000000'
    };
    let menuDiy = this.data.diy
    menuDiy[this.data.show_num].vcon.push(mt)
    this.setData({
      diy: menuDiy
    })
  },
  /**
   * --自由面板--
   * 添加图片
   */
  addFreePanelImage(e) {
    let mt = {
      img: '1',
      x: '0',
      y: '0',
      w: '100',
      h: '100',
      url: '../../../images/noimg2.png',
      event: '',
      event_url: '',
      type: '',
      border: 'none'
    };
    let menuDiy = this.data.diy
    menuDiy[this.data.show_num].vcon.push(mt)
    this.setData({
      diy: menuDiy
    })
  },
  /**
   * --自由面板--
   * 高度调节
   */
  freepanelHeightChange(e) {
    let ui = this.data.diy;
    console.log()
    ui[this.data.show_num].height = e.detail.value
    this.setData({
      diy: ui
    })
  },
  /**
   * --自由面板--
   * 文本内容修改
   */
  onFreePanelTextChange: function (e) {
    console.log(e)
    let ui = this.data.diy;
    ui[this.data.show_num].vcon[e.currentTarget.dataset.index].content = e.detail
    this.setData({
      diy: ui
    })

  },
  freePanelImageHeightChange: function (e) {
    console.log(e.currentTarget.dataset.index);
    let mt = e.currentTarget.dataset.index;
    let ui = this.data.diy;
    ui[this.data.show_num].vcon[mt].h = e.detail.value
    this.setData({
      diy: ui
    })
  },
  freePanelImageWidthChange: function (e) {
    console.log(e.currentTarget.dataset.index);
    let mt = e.currentTarget.dataset.index;
    let ui = this.data.diy;
    ui[this.data.show_num].vcon[mt].w = e.detail.value
    this.setData({
      diy: ui
    })
    console.log(this.data.diy)
  },
  deleteFreePanelEle(e) {
    let ui = this.data.diy;
    ui[e.currentTarget.dataset.index].vcon.splice(e.currentTarget.dataset.cellindex, 1)
    this.setData({
      diy: ui
    })
  },
  // 手指按下
  handleTouchStart: function (e) {
    this.startTime = e.timeStamp;
  },

  //手指离开
  handleTouchEnd: function (e) {
    this.endTime = e.timeStamp;
  },
  setTxtColor: function (e) {

    let color = e.currentTarget.dataset.val;
    let index = e.currentTarget.dataset.index;
    console.log("123123")
    console.log(color)
    console.log(index)
    console.log(this.data.show_num)
    let ui = this.data.diy;
    ui[this.data.show_num].vcon[index].bgcolor = color
    this.setData({
      diy: ui
    })
  },
  onClose(event) {
    if (event.detail === 'confirm') {
      // 异步关闭弹窗
      setTimeout(() => {
        this.setData({
          callPanelShow: false
        });
      }, 1000);
    } else {
      this.setData({
        callPanelShow: false
      });
    }
  },
  chooseCallNumber(e) {
    this.setData({
      callPanelShow: true
    })
  },
  onCallNumberChange: function (e) {
    console.log(e.detail)
    let goodsDiy = this.data.diy;
    goodsDiy[this.data.show_num].vcon[this.data.tmpFreePanelSubIndex].type = 2; //商品是0  页面是1 打电话2 地图3
    goodsDiy[this.data.show_num].vcon[this.data.tmpFreePanelSubIndex].event = e.detail;
    this.setData({
      diy: goodsDiy
    })
  },
  chooseLocation() {
    const that = this
    wx.chooseLocation({
      success(res) {
        console.log(res)
        let goodsDiy = that.data.diy;
        goodsDiy[that.data.show_num].vcon[that.data.tmpFreePanelSubIndex].type = 3; //商品是0  页面是1 打电话2 地图3
        goodsDiy[that.data.show_num].vcon[that.data.tmpFreePanelSubIndex].event = res.longitude + "#" + res.latitude + "#" + res.name + "#" + res.address;
        that.setData({
          diy: goodsDiy
        })
      }
    })
  },
  openLocation(e) {
    console.log(e)
    const value = e.detail.value
    console.log(value)
    wx.openLocation({
      longitude: Number(value.longitude),
      latitude: Number(value.latitude),
      name: value.name,
      address: value.address
    })
  },
  clickEvent(type, event) {
    console.log("clickEvent")
    console.log(type)
    let tmp = this.data.diy;
    if (type == "" || type == undefined) {
      console.log("无效果")
    } else if (type == '0') { //商品跳转
      console.log(type)
      this.goProductPage(event)
    } else if (type == '1') { //页面跳转
      for (var i = 0; i < this.data.all.length; i++) {
        if (i == event) {
          if (this.data.all[i].name == '商品列表' || this.data.all[i].name == '管理中心') {
            wx.navigateTo({
              url: this.data.all[event].url
            })
          } else {
            // wx.setStorageSync('tmpCurrentPageName', this.data.all[i].name)
            app.globalData.diyId = this.data.diyId;
            app.globalData.diyProduct = this.data.diyProduct;
            app.globalData.diyEdit = this.data.diyEdit;
            app.globalData.diyPageI = i;
            if (this.data.all[i].type == '主页') {
              wx.switchTab({
                url: '../../../pages/com/home/index?diyId=' + this.data.diyId + '&diyEdit=' + this.data.diyEdit
              })
            } else if (this.data.all[i].type == '一级页面') {
              wx.navigateTo({
                url: '../../../pages/com/one/index?diyId=' + this.data.diyId + '&diyEdit=' + this.data.diyEdit
              })
            } else if (this.data.all[i].type == '二级页面') {
              wx.navigateTo({
                url: '../../../pages/com/two/index?diyId=' + this.data.diyId + '&diyEdit=' + this.data.diyEdit
              })
            } else if (this.data.all[i].type == '三级页面') {
              wx.navigateTo({
                url: '../../../pages/com/three/index?diyId=' + this.data.diyId + '&diyEdit=' + this.data.diyEdit
              })
            } else {
              wx.switchTab({
                url: '../../../pages/com/home/index?diyId=' + this.data.diyId + '&diyEdit=' + this.data.diyEdit
              })
            }
          }
        }
      }
    } else if (type == '2') {
      wx.makePhoneCall({
        phoneNumber: event // 仅为示例，并非真实的电话号码
      })
    } else if (type == '3') {
      let tmpevent = event;
      wx.openLocation({
        longitude: Number(tmpevent.split("#")[0]),
        latitude: Number(tmpevent.split("#")[1]),
        name: tmpevent.split("#")[2],
        address: tmpevent.split("#")[3]
      })
    } else if (type == '4') { //新零售模板
      //event 存的是id 
      app.globalData.diyId = event;
      app.globalData.diyProduct = 1;
      app.globalData.diyEdit = "false";
      app.globalData.diyPageI = -1;
      wx.navigateTo({
        url: '../../../pages/com/home/index',
      })
    } else if (type == '5') { //新微站模板
      //event 存的是id 
      app.globalData.diyId = event;
      app.globalData.diyProduct = 2;
      app.globalData.diyEdit = "false";
      app.globalData.diyPageI = -1;
      wx.navigateTo({
        url: '../../../pages/com/home/index',
      })
    } else {
      console.log("无效果");
    }
  },
  logMethod: function (e) {
    console.log("com-home-" + e);
  },
  log: function (e) {
    console.log(e)
  },
  goback: function (e) {
    app.globalData.diyId = '';
    app.globalData.diyEdit = '';
    app.globalData.diyProduct = '';
    wx.redirectTo({
      url: '../../../pages/manage/xcx-man/index',
    })
  },
  goedit: function (e) {
    let pro = 0;
    db.collection('index_diy').where({
      _openid: wx.getStorageSync("openid") // 填入当前用户 openid
    }).count().then(res => {
      console.log(res.total)
      if (res.total > 2) {
        wx.showToast({
          icon: 'none',
          title: '最多免费拥有2个模板哦'
        });
      } else {
        db.collection('index_diy').doc(app.globalData.diyId).get().then(res => {
          console.log(res)
          if (res.data.all.length > 0) { //判断是否是首次diy编辑
            pro = res.data.product;
            db.collection('index_diy').add({
              // data 字段表示需新增的 JSON 数据
              data: {
                type: "user",
                createtime: util.formatTime(new Date()),
                all: res.data.all,
                name: res.data.name,
                product: res.data.product,
                files: []
              }
            })
              .then(res => {
                console.log(res);
                wx.setStorageSync('diyId', res._id);
                app.globalData.diyId = res._id;
                app.globalData.diyProduct = pro;
                app.globalData.diyPageI = -1;
                app.globalData.diyEdit = "true";
                wx.navigateTo({
                  url: `/pages/com/home/index`
                });
              })


          } else { //初始化些数据
            wx.showToast({
              title: '当前模板不可用',
            });
          }
        })
      }
    })
  },
  gobuy: function (e) {
    wx.makePhoneCall({
      phoneNumber: '17643036681' // 
    })
  }
});